package io.kiki.sba.registry.observer.impl;

import io.kiki.sba.registry.lifecycle.Lifecycle;
import io.kiki.sba.registry.lifecycle.LifecycleController;
import io.kiki.sba.registry.lifecycle.LifecycleState;
import io.kiki.sba.registry.lifecycle.impl.AbstractLifecycle;
import io.kiki.sba.registry.observer.Observable;
import io.kiki.sba.registry.observer.UnblockingObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


public class AbstractLifecycleObservable extends AbstractLifecycle implements Observable, Lifecycle {
    private static final Logger logger = LoggerFactory.getLogger(AbstractLifecycleObservable.class);
    final List<UnblockingObserver> unblockingObserverList = new CopyOnWriteArrayList<>();

    public AbstractLifecycleObservable() {
    }

    public AbstractLifecycleObservable(LifecycleState lifecycleState, LifecycleController lifecycleController) {
        super(lifecycleState, lifecycleController);
    }

    @Override
    public void addObserver(UnblockingObserver observer) {
        unblockingObserverList.add(observer);
    }

    @Override
    public void removeObserver(UnblockingObserver observer) {
        unblockingObserverList.remove(observer);
    }

    protected void notifyObservers(final Object message) {

        for (final Object observer : unblockingObserverList) {
            try {
                ((UnblockingObserver) observer).update(AbstractLifecycleObservable.this, message);
            } catch (Throwable e) {
                logger.error("[notifyObservers][{}]", observer, e);
            }
        }
    }
}
